package com.pingpang.websocketchat.send.impl;

import java.net.InetSocketAddress;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.pingpang.redis.RedisPre;
import com.pingpang.websocketchat.ChannelManager;
import com.pingpang.websocketchat.Message;
import com.pingpang.websocketchat.send.ChatSend;

import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

/**
 * 绑定操作
 * @author dell
 */
public class ChatSendBind extends ChatSend{

	@Override
	public void send(Message message, ChannelHandlerContext ctx) throws JsonProcessingException {
		
	   InetSocketAddress ipSocket = (InetSocketAddress)ctx.channel().remoteAddress();
	   String clientIp = ipSocket.getAddress().getHostAddress();
	   
	   message.setFrom(userService.getUser(message.getFrom()));
	   message.getFrom().setIp(clientIp);
        
	   redisService.set(RedisPre.DB_USER+message.getFrom().getUserCode(), message.getFrom());
		
	   ChannelManager.addChannel(message.getFrom(), ctx.channel());
		
		/**
		 * 获取离线消息，并推送
		 */
		List<Message> outMsg=userMsgService.getUserOutMsg(message.getFrom());
		if(null!=outMsg && !outMsg.isEmpty()) {
			
			Set<String> messageIDs=new HashSet<String>();
			Map<String,Object> updateMap=new HashMap<String, Object>();
			updateMap.put("status", "1");
			updateMap.put("IP", clientIp);
				for(Message m : outMsg) {
					messageIDs.add(m.getId());
					m.setCmd("2");//当作离线通知和下线提醒
					ctx.channel().writeAndFlush(new TextWebSocketFrame(this.getMapper().writeValueAsString(m)));		
			  }
				/**
				 * 更新数据状态
				 */
				updateMap.put("ids", messageIDs);
				userMsgService.upOutMsg(updateMap); 				
		}
	}

}
